const tool = require('../tools/tool')

function extractTables(sql) {
    // 去除多余的空格和换行符，并将所有字符转换为小写
    sql = sql.replace(/\s+/g, ' ').trim().toLowerCase();

    // 定义正则表达式，匹配常见的 SQL 操作语句及其后面的表名
    const regexMap = {
        select: /\bselect\b.*?\bfrom\b\s*`?([a-zA-Z0-9_]+)`?/gi,
        insert: /\binsert\s+into\b\s*`?([a-zA-Z0-9_]+)`?/gi,
        update: /\bupdate\b\s*`?([a-zA-Z0-9_]+)`?/gi,
        delete: /\bdelete\b.*?\bfrom\b\s*`?([a-zA-Z0-9_]+)`?/gi,
        describe: /\bdescribe\b\s*`?([a-zA-Z0-9_]+)`?/gi
    };

    const tables = {
        op: [],
        select: [],
        insert: [],
        update: [],
        delete: [],
        describe: []
    };

    let match;
    for (const [op, regex] of Object.entries(regexMap)) {
        while ((match = regex.exec(sql)) !== null) {
            tables[op].push(match[1]);
            if (!tables.op.includes(op)) {
                tables.op.push(op);
            }
        }
    }

    return tables;
}

const data = {
    data: {},
    set(table, sql, data) {
        if (this.data[table] === undefined) this.data[table] = {}
        this.data[table][sql] = data
        // console.log('添加缓存', table, sql)
    },
    remove(table) {
        // console.log('remove',table)
        delete this.data[table]
    },
    get(table, sql) {
        if (this.data[table] === undefined) return undefined
        if (this.data[table][sql] === undefined) return undefined
        return this.data[table][sql]
    }
}

module.exports = {
    reset(table){
        data.remove(table)
    },
    update(sql, res) {
        // console.log(11)
        let op = extractTables(sql)
        for (let i = 0; i < op.op.length; i++) {
            let currentOp = op.op[i]
            let tables = op[currentOp]
            if (currentOp == 'delete' || currentOp == 'update' || currentOp == 'insert') {
                for (let i1 = 0; i1 < tables.length; i1++)data.remove(tables[i1])
            } else {
                data.set(tables[0], sql, tool.deepCopy(res))
            }
        }
        // console.log(data.data)
    },
    get(sql) {
        // return undefined
        let op = extractTables(sql)
        if (op.op != 'select' && op.op != 'describe') return undefined
        let tableName = ''
        if (op.select.length) tableName = op.select[0]
        if (op.update.length) tableName = op.update[0]
        if (op.delete.length) tableName = op.delete[0]
        if (op.insert.length) tableName = op.insert[0]
        if (op.describe.length) tableName = op.describe[0]
        // console.log(tableName, sql)
        return tool.deepCopy(data.get(tableName, sql))
    }
}